package com.ym.b2b.order.service.impl;

import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.ym.b2b.buyer.dao.EmCBuyerAddressDao;
import com.ym.b2b.buyer.dao.EmCBuyerDao;
import com.ym.b2b.buyer.sqlbean.EmCBuyer;
import com.ym.b2b.buyer.sqlbean.EmCBuyerAddress;
import com.ym.b2b.cache.configcache.WebAppConfig;
import com.ym.b2b.commons.exception.BaseException;
import com.ym.b2b.commons.service.BaseService;
import com.ym.b2b.commons.util.CheckData;
import com.ym.b2b.haipai.db.DBFactroy;
import com.ym.b2b.haipai.vo.XCOrderParam;
import com.ym.b2b.order.DefaultTradeRequestImpl;
import com.ym.b2b.order.TradeRequest;
import com.ym.b2b.order.dao.EmSOrderAddressDao;
import com.ym.b2b.order.dao.EmSOrderConfirmItemDao;
import com.ym.b2b.order.dao.EmSOrderDao;
import com.ym.b2b.order.dao.EmShoppingCartDao;
import com.ym.b2b.order.service.EmSOrderService;
import com.ym.b2b.order.sqlbean.EmSOrder;
import com.ym.b2b.order.sqlbean.EmSOrderAddress;
import com.ym.b2b.order.sqlbean.EmSOrderConfirmItem;
import com.ym.b2b.order.sqlbean.EmSShoppingCart;
import com.ym.b2b.order.vo.OrderInfoVO;
import com.ym.b2b.order.xc.sqlbean.XCReturnModel;
import com.ym.b2b.product.dao.EmKStorageDao;
import com.ym.b2b.product.dao.ProductDao;
import com.ym.b2b.product.sqlbean.EmBProduct;
import com.ym.b2b.product.sqlbean.EmKStorage;
import com.zc.commons.base.Page;
import com.zc.commons.base.Result;

@Service
public class EmSOrderServiceImpl extends BaseService implements EmSOrderService {

    @Autowired
    private EmSOrderDao            orderDao;

    @Autowired
    private EmKStorageDao          emKStorageDao;

    @Autowired
    private EmShoppingCartDao      emShoppingCartDao;

    @Autowired
    private EmSOrderConfirmItemDao emSOrderItemDao;

    @Autowired
    private EmSOrderAddressDao     emSOrderAddressDao;

    @Autowired
    private EmCBuyerAddressDao     emCBuyerAddressDao;

    @Autowired
    private EmCBuyerDao            emCBuyerDao;

    @Autowired
    private ProductDao             productDao;

    @Resource
    private TradeRequest           defaultTradeRequest;

    private Logger                 logger = Logger.getLogger(getClass());

    @Override
    public Page<EmSOrder> searchPageOrders(EmSOrder emSOrder, Page<EmSOrder> page) throws BaseException {
        try {
            return orderDao.searchPageOrders(emSOrder, page);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("订单查询异常");
        }

    }

    @Override
    @Transactional
    public Result generateOrder(OrderInfoVO vo) throws BaseException {
        Result ret = new Result();
        // STEP .1 数据检查 购物车、收货地址
        // 获取购物车列表
        EmSShoppingCart emSShoppingCart = new EmSShoppingCart();
        emSShoppingCart.setIsBranch(vo.getUser().getIsBranch());
        emSShoppingCart.setBuyerCode(vo.getUser().getBuyerCode());
        emSShoppingCart.setPayType(vo.getUser().getPayType());
        emSShoppingCart.setList(vo.getShoppingCartList());
        List<EmSShoppingCart> shoppingCartList = emShoppingCartDao.searchShoppingCart(emSShoppingCart);
        ret = checkOrderData(vo, shoppingCartList);

        if (ret.getCode().equals(Result.CODE_100)) {
            return ret;
        }

        Long orderId = orderDao.getEmSOrderId(); // 获取订单号

        vo.setOrderFromOrderId(orderId);// 设置 ordercode
        ret.putData("orderCode", vo.getOrderCode());

        Double confirmMoney=emShoppingCartDao.countShoppintCartTotalMoeny(emSShoppingCart);

        vo.setTotalMoney(confirmMoney);// 总金额
        vo.setConfirmMoney(confirmMoney);// 确认金额
        ret.putData("money",vo.getTotalMoney());
        vo.setTradeFeeMoney(vo.getTotalMoney() * 5 / 1000);

        addEmSOrder(vo);// 新增订单 总单

        List<EmSOrderConfirmItem> list = new ArrayList<EmSOrderConfirmItem>();

        addEmSOrderItem(vo, list, shoppingCartList); // 新增订单确认明细 并赋值给list

        addEmSOrderAddress(vo); // 新增收货地址

        // 更新订单状态为10(已确认)
        EmSOrder emSOrder = new EmSOrder();
        emSOrder.setOrderId(vo.getOrderId());
        emSOrder.setOrderCode(vo.getOrderCode());
        emSOrder.setStatus(10d);
        
        // 在application_config.xml中控制判断什么时候对接ERP下订单 ,false 则在支付后下单, ture则在确认时下单
        if (DefaultTradeRequestImpl.isBooking()) {
            Result erpResult = defaultTradeRequest.bookingErpOrder(vo, list);
            if(!"200".equals(erpResult.getCode())){
            	logger.error("ERP下单失败:" + erpResult.getResult());
            	throw new BaseException("ERP下单失败:" + erpResult.getResult());
            }
            //*** ERP下订单成功：跟新erp系统的内部单据号 *******//
            XCReturnModel xcReturnModel = (XCReturnModel) erpResult.getData().get("orderRet");
            logger.info("xcReturnModel: " + JSON.toJSONString(xcReturnModel));
            if (null != xcReturnModel && !"".equals(xcReturnModel.getOrderCode())) {
            	String returnCode = xcReturnModel.getOrderCode();
                emSOrder.setOrderCodeErp(returnCode.substring(returnCode.indexOf("-")+1) );
            }
        }
        
        try {
            orderDao.updateEmSOrder(emSOrder);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("更新订单信息失败!" + e.getMessage());
        }

        // 删除购物车
        EmSShoppingCart emSShoppingCart1 = new EmSShoppingCart();
        emSShoppingCart1.setBuyerCode(vo.getUser().getBuyerCode());
        emSShoppingCart1.setList(vo.getShoppingCartList());
        try {
            emShoppingCartDao.deleteShoppingCart(emSShoppingCart1);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("删除购物车信息失败!" + e.getMessage());
        }

        return ret;
    }

    /**
     * 数据检查
     * 
     * @Title: checkOrderData
     * @Description: TODO
     * @Param @param vo
     * @Param @return
     * @Return Result
     * @Throws
     */
    public Result checkOrderData(OrderInfoVO vo, List<EmSShoppingCart> shoppingCartList) {
        Result ret = new Result();
        if (null == vo.getUser().getBuyerCode()) {
            ret.setCodeResult(Result.CODE_100, "缺少采购商编号!");
            return ret;
        }
        if (null == vo.getBuyerAddressId() || "".equals(vo.getBuyerAddressId())) {
            ret.setCodeResult(Result.CODE_100, "未选择收货地址!!");
            return ret;
        }
        // 检查购物车 是否为空

        if (CollectionUtils.isEmpty(shoppingCartList)) {
            ret.setCodeResult(Result.CODE_100, "购物车没有数据  无法继续下一步!");
            return ret;
        }
        
        for(EmSShoppingCart emSShoppingCart: shoppingCartList){
        	EmBProduct svo = new EmBProduct();
        	svo.setProductCode(emSShoppingCart.getProductCode());
        	EmBProduct emBProduct = productDao.showProductDetailConcise(svo);

			if(emBProduct.getIsSale() == 0){
				ret.setCodeResult(Result.CODE_100, "SORRY, " +  emSShoppingCart.getProductCode() + emSShoppingCart.getChsName() + "该商品已经下架,无法购买!");
				return ret;
			}
        }
        return ret;
    }

    @Override
    public Result getInfoForOrder(OrderInfoVO vo) throws BaseException {
        Result ret = new Result();
        ret = checkOrderInfo(vo);
        if (ret.getCode().equals(Result.CODE_100)) {
            return ret;
        }

        // 获取购物车列表
        EmSShoppingCart emSShoppingCart = new EmSShoppingCart();
        emSShoppingCart.setIsBranch(vo.getUser().getIsBranch());
        emSShoppingCart.setBuyerCode(vo.getUser().getBuyerCode());
        emSShoppingCart.setPayType(vo.getUser().getPayType());
        emSShoppingCart.setList(vo.getShoppingCartList());
        List<EmSShoppingCart> shoppingCartList = emShoppingCartDao.searchShoppingCart(emSShoppingCart);

        if (CollectionUtils.isEmpty(shoppingCartList)) {
            ret.setCodeResult(Result.CODE_100, "对不起,您的购物车是空的,无法进行下一步操作!");
            return ret;
        }
        vo.setShoppingCartList(shoppingCartList);

        ret = checkBusinessScop(vo);// 检查购物车商品 是否在采购商的 经营范围
        if (ret.getCode().equals(Result.CODE_100)) {
            return ret;
        }

        // 获取采购商 和 采购商信息
        EmCBuyer emCBuyer = new EmCBuyer();
        emCBuyer.setBuyerCode(vo.getUser().getBuyerCode());
        emCBuyer = emCBuyerDao.showEmCBuyerDetail(emCBuyer);

        EmCBuyerAddress emCBuyerAddress = new EmCBuyerAddress();
        emCBuyerAddress.setBuyerCode(vo.getUser().getBuyerCode());
        List<EmCBuyerAddress> addressList = emCBuyerAddressDao.searchEmCBuyerAddress(emCBuyerAddress);

        ret.putData("emCBuyer", emCBuyer);
        ret.putData("addressList", addressList);

        ret.putData("shoppingCartList", shoppingCartList);
        ret.putData("shoppingCartJson", JSON.toJSONString(shoppingCartList));
        ret.putData("sumMoney", emShoppingCartDao.countShoppintCartTotalMoeny(emSShoppingCart));
        Page<EmSShoppingCart> page = new Page<EmSShoppingCart>();
        page.setRows(shoppingCartList);
        ret.setResultPage(page);
        return ret;
    }

    @Override
    @Transactional
    public Result cancelOrder(OrderInfoVO vo) throws BaseException {
        Result result = new Result();
        // 检查订单状态是否能够取消

        EmSOrder emSOrder = new EmSOrder();
        emSOrder.setOrderCode(vo.getOrderCode());
        EmSOrder emSOrderd = orderDao.searchOrderDetail(emSOrder);
        vo.setErpCode(emSOrderd.getOrderCodeErp());
        if (emSOrderd.getStatus().doubleValue() > 10) {// 大于 已确认
            result.setCodeResult(Result.CODE_100, "当前订单状态为：" + emSOrderd.getStrStatus() + ".不能删除 可联系管理员！");
            return result;
        }
        emSOrder.setStatus(-1d);

        try {
            orderDao.updateEmSOrder(emSOrder);
            /* 在application_config.xml中控制判断什么时候对接ERP下订单 ,false 则在支付后下单, ture则在确认时下单  
             * 对应到取消订单,表现为 true需要调用ERP接口, false不需要
             */
            if (DefaultTradeRequestImpl.isBooking()) {
            	Result erpResult = defaultTradeRequest.cancelOrder(vo);
            	if(!"200".equals(erpResult.getCode())){
            		result.setCodeResult(erpResult.getCode(), erpResult.getResult());
            		logger.error("ERP取消订单失败:" + erpResult.getResult());
            		throw new BaseException("ERP取消订单失败:" + erpResult.getResult());
            	}
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("订单:" + vo.getOrderCode() + "  取消操作异常!" + e.getMessage());
        }
        
        return result;
    }

    @SuppressWarnings("unused")
    private Result checkOrderInfo(OrderInfoVO vo) {
        Result ret = new Result();
        // 校验资质
        if (StringUtils.isBlank(vo.getUser().getBuyerCode())) {
            ret.setCodeResult(Result.CODE_100, "对不起:您不是采购商,没有采购商品权限!");
            return ret;
        }
        if (StringUtils.isEmpty(vo.getUser().getBuyerCode())) {
            ret.setCodeResult(Result.CODE_100, "对不起：您的采购资质还未通过审核,请联系官方！");
            return ret;
        }
        // 校验 证照过期情况  XXX 相关配置在application_config.xml中配置
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (null != WebAppConfig.getConfigMapServiceRouter().get("CHECK_LICENSE_DATE")
            && "true".equals(WebAppConfig.getConfigMapServiceRouter().get("CHECK_LICENSE_DATE"))) {

            if (null != vo.getUser().getLicenseEndDate()) {
                if (!CheckData.isDateBefore(vo.getUser().getLicenseEndDate())) {
                    /** 不合法 已过期 **/
                    ret.setCodeResult(Result.CODE_100, "您当前的许可证结束日期为：" + sdf.format(vo.getUser().getLicenseEndDate())
                                                       + ".当前已经过期,请及时提交新的许可证!");
                    return ret;
                }

            } else {
                /** 日期不合法 海派医药不需要验证 **/
                ret.setCodeResult(Result.CODE_100, "无法查询到您登机的证照日期,请联系官方完善数据后 再重新登陆!");
                return ret;
            }
        }
        if (null != WebAppConfig.getConfigMapServiceRouter().get("CHECK_LICENSE_DATE")
            && "true".equals(WebAppConfig.getConfigMapServiceRouter().get("CHECK_LICENSE_DATE"))) {
            if (null != vo.getUser().getBusinessEndDate()) {
                if (!CheckData.isDateBefore(vo.getUser().getBusinessEndDate())) {
                    ret.setCodeResult(Result.CODE_100, "您当前的营业执照结束日期为：" + sdf.format(vo.getUser().getBusinessEndDate())
                                                       + ".当前已经过期,请及时提交新的许可证!");
                    return ret;
                }
            } else {
                /** 日期不合法 **/
                ret.setCodeResult(Result.CODE_100, "您当前的营业执照结束日期为空，审核的数据不合法，请联系管理员或拨打客服热线。");
                return ret;
            }
        }
        return ret;
    }

    /**
     * @Title: checkBusinessScop
     * @Description: 检查 采购商的 经营范围 是否符合购物车内的商品
     * @Param @param vo
     * @Param @return
     * @Return Result
     * @Throws
     */
    private Result checkBusinessScop(OrderInfoVO vo) {

        Result ret = new Result();
        // XXX 相关配置在application_config.xml中配置
        if (null != WebAppConfig.getConfigMapServiceRouter().get("CHECK_BUSINESS_SCOP")
            && "false".equals(WebAppConfig.getConfigMapServiceRouter().get("CHECK_BUSINESS_SCOP"))) {
            return ret;
        }
        ret.setResult("");
        EmCBuyer emCBuyer = new EmCBuyer();
        emCBuyer.setBuyerCode(vo.getUser().getBuyerCode());
        emCBuyer = emCBuyerDao.showEmCBuyerDetail(emCBuyer);

        EmBProduct emBProduct = new EmBProduct();
        for (EmSShoppingCart ess : vo.getShoppingCartList()) {
            emBProduct.setProductCode(ess.getProductCode());
            emBProduct.setBusinesscope(emCBuyer.getProductionScope());
            EmBProduct emBProduct1 = productDao.showProductDetailConcise(emBProduct);

            if (null == emBProduct1) {
                emBProduct.setBusinesscope(null);
                emBProduct = productDao.showProductDetailConcise(emBProduct);
                ret.setCodeResult(Result.CODE_100,
                                  ret.getResult() + "编号：'" + ess.getProductCode() + "';产品名：'" + ess.getChsName()
                                          + "'的所属范围为：" + emBProduct.getBusinesscope() + ";</br>");

            }
        }
        if (ret.getCode().equals(Result.CODE_100)) {
            ret.setResult(ret.getResult() + "以上产品不在您的经营许可范围内;您的经营许可为：" + emCBuyer.getProductionScope());

        }
        return ret;
    }

    /*** 处理 本地系统 部分 ***/
    @SuppressWarnings("static-access")
    private Result dealOrder(OrderInfoVO vo, String productCodes) {
        Result ret = new Result();
        XCOrderParam XCOrderParam = new XCOrderParam();
        Connection conn = null;
        try {
            conn = DBFactroy.getHaiPaiCon();
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
        ResultSet rs = null;
        try {
            /** NO.1************* 告知本地系统 下单 ************/
            logger.debug("-----下单报文：webdjpro('" + XCOrderParam.CUSTOMER_ORDER + "','" + vo.getUser().getBuyerCode()
                         + "','" + vo.getOrderCode() + "','" + productCodes + "',：x,:y,:z)");

            CallableStatement query = conn.prepareCall("{call webdjpro(?,?,?,?,?,?,?)}");
            query.setString(1, XCOrderParam.CUSTOMER_ORDER);
            query.setString(2, vo.getUser().getBuyerCode());
            query.setString(3, vo.getOrderCode());
            query.setString(4, productCodes);
            query.registerOutParameter(5, java.sql.Types.VARCHAR);
            query.registerOutParameter(6, java.sql.Types.VARCHAR);
            query.registerOutParameter(7, java.sql.Types.VARCHAR);
            query.execute();

            XCOrderParam.setCurSqlRet(query.getString(5));
            XCOrderParam.setCurSqlErrMsg(query.getString(6));
            XCOrderParam.setErpCode(query.getString(7));
            ret.putData("orderRet", XCOrderParam);
            if (XCOrderParam.getCurSqlRet().equals("1")) {
                EmSOrderConfirmItem emSOrderConfirmItem = new EmSOrderConfirmItem();
                emSOrderConfirmItem.setOrderCode(vo.getOrderCode());
                emSOrderConfirmItem.setOrderCodeErp(XCOrderParam.getErpCode());
                // emSOrderItemDao.updateEmSOrderConfirmItem(emSOrderConfirmItem);
            } else {
                ret.setCodeResult("100", XCOrderParam.getCurSqlErrMsg());
                return ret;
            }

            /** NO.2************* 跟新 产品 批号 和有效期 ************/
            PreparedStatement pstmt = conn.prepareStatement("{call webdjzt(?,?,?)}");
            pstmt.setString(1, XCOrderParam.CUSTOMER_ORDER);//
            pstmt.setString(2, vo.getUser().getBuyerCode());
            pstmt.setString(3, vo.getOrderCode());
            rs = pstmt.executeQuery();
            while (rs.next()) {
                logger.debug("-----更新商品明细：" + rs.getString("spbh") + "|" + rs.getString("sxrq") + "|"
                             + rs.getString("pihao"));

                EmSOrderConfirmItem emSOrderConfirmItem = new EmSOrderConfirmItem();
                emSOrderConfirmItem.setProductCode(rs.getString("spbh"));
                emSOrderConfirmItem.setOrderCode(vo.getOrderCode());
                Integer isExit = emSOrderItemDao.searchEmSOrderConfirmItemBatchNum(emSOrderConfirmItem);

                String dateStr = "0000-00-00";
                if (rs.getString("sxrq") != null && !rs.getString("sxrq").replaceAll(" ", "").equals("")) {
                    dateStr = rs.getString("sxrq");
                }
                if (isExit > 0) {
                    // 修改批次
                    emSOrderConfirmItem.setValidateStr(dateStr);
                    emSOrderConfirmItem.setBatchNumber(rs.getString("pihao"));
                    emSOrderConfirmItem.setConfirmAmount(Double.parseDouble(rs.getString("shl")));
                    emSOrderConfirmItem.setConfirmMoney(Double.parseDouble(rs.getString("hsje")));
                    emSOrderConfirmItem.setOrderCodeErp(XCOrderParam.getErpCode());

                    emSOrderItemDao.updateEmSOrderConfirmItem(emSOrderConfirmItem);
                } else {
                    // 新增批次
                    logger.info("---------------收货订单明细-多批次新增");
                    emSOrderConfirmItem = emSOrderItemDao.searchEmSOrderConfirmItem(emSOrderConfirmItem).get(0);

                    emSOrderConfirmItem.setValidateStr(dateStr);
                    emSOrderConfirmItem.setBatchNumber(rs.getString("pihao"));
                    emSOrderConfirmItem.setConfirmAmount(Double.parseDouble(rs.getString("shl")));
                    emSOrderConfirmItem.setConfirmMoney(Double.parseDouble(rs.getString("hsje")));
                    emSOrderConfirmItem.setOrderCodeErp(XCOrderParam.getErpCode());
                    emSOrderConfirmItem.setOrderConfirmItemId(null);
                    emSOrderItemDao.saveOrUpdateEmSOrderConfrimItem(emSOrderConfirmItem);
                }
            }
            if (rs != null) {
                rs.close();
            }
            if (conn != null) {
                conn.close();
            }
            return ret;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("通知本地系统失败或修改销售单明细失败：" + e.getMessage());
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
                throw new BaseException("关闭本地数据库连接异常:" + e.getMessage());
            }

        }
    }

    /**
     * 生成 web订单 过程
     * 
     * @Title: execeteWebOrder
     * @Description: TODO
     * @Param @param vo
     * @Param @throws Exception
     * @Return void
     * @Throws
     */
    private void executeWebOrder(OrderInfoVO vo) {

        String salePriceCloum = ""; // 什么价格结算 订单

        if (vo.getUser().getPayType() == 0) {// 欠款
            salePriceCloum = "arrears_price";
        } else if (vo.getUser().getPayType() == 1) {// 现金
            salePriceCloum = "cash_price";
        } else if (vo.getUser().getIsBranch() == 1) {
            salePriceCloum = "shop_price";
        } else {
            salePriceCloum = "sale_price";
        }

    }

    /**
     * 新增订单 总单
     * 
     * @Title: addEmSOrder
     * @Description: TODO
     * @Param @param vo
     * @Param @throws Exception
     * @Return void
     * @Throws
     */
    private void addEmSOrder(OrderInfoVO vo) {

        try {
            EmSOrder emSOrder = new EmSOrder();
            emSOrder.setOrderId(vo.getOrderId());
            emSOrder.setOrderCode(vo.getOrderCode());
            emSOrder.setBuyerCode(vo.getUser().getBuyerCode());
            emSOrder.setOrderNotes(vo.getOrderNotes());
            emSOrder.setTotalMoney(vo.getTotalMoney());
            emSOrder.setConfirmMoney(vo.getConfirmMoney());
            emSOrder.setTradeFeeMoney(vo.getTradeFeeMoney());

            emSOrder.setIsInvoice(vo.getIsInvoice());// 是否开票
            emSOrder.setInvoiceType(vo.getInvoiceType());// 是否开票
            emSOrder.setIsInvoiceAlone(vo.getIsInvoiceAlone());// 是否单独开票
            emSOrder.setInvoiceManLoginName(vo.getInvoiceManLoginName());// 发票名称
            emSOrder.setSalesman(vo.getUser().getSaleMan());// 业务员
            // emSOrder.setSalesmanPhone(vo.getSalesmanPhone());// 业务员电话
            // 新增订单
            emSOrder.setCreateUser(vo.getUser().getUserId());
            emSOrder.setCreateDate(new Date());
            emSOrder.setUpdateDate(new Date());
            emSOrder.setTotalIntegral(0d);
            orderDao.insertEmSOrder(emSOrder);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("保存订单信息异常：" + e.getMessage());
        }
    }

    /**
     * 新增订单 明细
     * 
     * @Title: addEmSOrderItem
     * @Description: TODO
     * @Param @param vo
     * @Param @throws BaseException
     * @Return void
     * @Throws
     */
    private void addEmSOrderItem(OrderInfoVO vo, List<EmSOrderConfirmItem> list, List<EmSShoppingCart> shoppingCartList){
        try {
            List<EmKStorage> emKStorages=new ArrayList<EmKStorage>();
            for (EmSShoppingCart a : shoppingCartList) {
                EmKStorage emKStorage=new EmKStorage();
                emKStorage.setProductCode(a.getProductCode());
                emKStorages =emKStorageDao.searchEmkStorageList(emKStorage);
                if(emKStorages==null||emKStorages.size()==0){
                    throw new BaseException("库存数据有问题，请稍后再试" );
                }
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                for(EmKStorage e:emKStorages){
                    EmSOrderConfirmItem emSOrderConfirmItem = new EmSOrderConfirmItem();
                    emSOrderConfirmItem.setOrderId(vo.getOrderId());
                    emSOrderConfirmItem.setProductCode(a.getProductCode());
                    emSOrderConfirmItem.setSalePrice(a.getSalePrice());
                    emSOrderConfirmItem.setOrderCode(vo.getOrderCode());
                    emSOrderConfirmItem.setOrderId(vo.getOrderId());
                    emSOrderConfirmItem.setPriceUseType(a.getNowPrice());
                    emSOrderConfirmItem.setCreateDate(new Date());
                    emSOrderConfirmItem.setProductName(a.getChsName());
                    // emSOrderConfirmItem.setPromoMoney(promoMoney);
                    if(e.getAmount()>=a.getAmount()){
                        emSOrderConfirmItem.setConfirmAmount(a.getAmount());
                        emSOrderConfirmItem.setConfirmMoney(a.getSalePrice() * emSOrderConfirmItem.getConfirmAmount());
                        emSOrderConfirmItem.setBatchNumber(e.getBatch());
                        emSOrderConfirmItem.setValidateStr(e.getExpirydate()==null?"":sdf.format(e.getExpirydate()));
                        list.add(emSOrderConfirmItem);
                        break;
                    }else{
                        emSOrderConfirmItem.setConfirmAmount(e.getAmount());
                        emSOrderConfirmItem.setConfirmMoney(a.getSalePrice() * emSOrderConfirmItem.getConfirmAmount());
                        emSOrderConfirmItem.setBatchNumber(e.getBatch());
                        emSOrderConfirmItem.setValidateStr(e.getExpirydate()==null?"":sdf.format(e.getExpirydate()));
                        Double amount=a.getAmount()-e.getAmount();
                        a.setAmount(amount);
                        list.add(emSOrderConfirmItem);
                    }
                }
            }
            if(list.size()>0){
                vo.setEmSOrderConfirmItemList(list);
                emSOrderItemDao.saveEmSOrderConfirmItemBatch(list);
            }else{
                throw new BaseException("请查看库存数据有效期" );
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("新增订单确认明细失败:[" + e.getMessage()+"]");
        }
    }

    /**
     * 新增 收货地址
     * 
     * @Title: addEmSOrderAddress
     * @Description: TODO
     * @Param @param vo
     * @Return void
     * @Throws
     */
    private void addEmSOrderAddress(OrderInfoVO vo) {

        try {
            EmCBuyerAddress emCBuyerAddress = new EmCBuyerAddress();

            emCBuyerAddress.setBuyerAddressId(vo.getBuyerAddressId());
            emCBuyerAddress = emCBuyerAddressDao.searchEmCBuyerAddressDetail(emCBuyerAddress);

            EmSOrderAddress emSOrderAddress = new EmSOrderAddress();
            emSOrderAddress.setOrderCode(vo.getOrderCode());
            if(emCBuyerAddress==null||emCBuyerAddress.getAddress()==null){
                logger.error("请添加收货地址！");
                throw new BaseException("请添加收货地址！");
            }
            emSOrderAddress.setAddress(emCBuyerAddress.getAddress());
            emSOrderAddress.setStation(emCBuyerAddress.getStation());
            emSOrderAddress.setAreaCode(emCBuyerAddress.getAreaCode());
            emSOrderAddress.setAreaName(emCBuyerAddress.getAreaName());
            emSOrderAddress.setConsignee(emCBuyerAddress.getConsignee());
            emSOrderAddress.setTrafficType(emCBuyerAddress.getTrafficType());
            emSOrderAddress.setLinkman(emCBuyerAddress.getLinkman());
            emSOrderAddress.setZip(emCBuyerAddress.getZip());
            emSOrderAddress.setShippingMethod(emCBuyerAddress.getShippingMethod());
            emSOrderAddress.setCreateUserId(vo.getUser().getUserId());
            emSOrderAddressDao.insertEmSOrderAddress(emSOrderAddress);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("新增收货地址异常：" + e.getMessage());
        }
    }

    @Override
    public Result searchOrderDetail(OrderInfoVO vo) throws BaseException {
        Result ret = new Result();

        try {
            logger.debug("orderCode:" + vo.getOrderCode());
            if (StringUtils.isBlank(vo.getOrderCode())) {
                ret.setCodeResult(Result.CODE_100, "订单号不能为空!");
                return ret;
            }
            // 订单总单
            EmSOrder emSOrder = new EmSOrder();
            emSOrder.setOrderCode(vo.getOrderCode());
            emSOrder = orderDao.searchOrderDetail(emSOrder);

            if (null == emSOrder) {
                ret.setCodeResult(Result.CODE_100, "订单不存在 请确认传入的订单号!");
                return ret;
            }
            // 销售明细
            EmSOrderConfirmItem emSOrderConfirmItem = new EmSOrderConfirmItem();
            emSOrderConfirmItem.setOrderCode(vo.getOrderCode());

            List<EmSOrderConfirmItem> orderConfigmItemList = emSOrderItemDao.searchEmSOrderConfirmItem(emSOrderConfirmItem);

            // 获取采购商 和 采购商信息
            EmCBuyer emCBuyer = new EmCBuyer();
            emCBuyer.setBuyerCode(emSOrder.getBuyerCode());

            emCBuyer = emCBuyerDao.showEmCBuyerDetail(emCBuyer);

            EmSOrderAddress emSOrderAddress = new EmSOrderAddress();
            emSOrderAddress.setOrderCode(vo.getOrderCode());
            emSOrderAddress = emSOrderAddressDao.showEmSOrderAddressDetail(emSOrderAddress);

            // 缺少缺货列表信息

            ret.setRows(orderConfigmItemList);
            ret.putData("emSOrderAddress", emSOrderAddress);
            ret.putData("emSOrder", emSOrder);
            ret.putData("emCBuyer", emCBuyer);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("获取订单明细异常：" + e.getMessage());
        }
        return ret;
    }

    @Override
    public Result chooseOrderFeeType(String orderCode, Integer orderType) throws BaseException {
        Result ret = new Result();
        EmSOrder emSOrder = new EmSOrder();
        emSOrder.setOrderCode(orderCode);
        emSOrder.setOrderType(orderType);
        try {
            orderDao.updateEmSOrder(emSOrder);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("选择支付类型失败");
        }

        return ret;
    }

    @Override
    public Result downloadOrderBatchZip(String orderCode) throws BaseException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result updateOrder(EmSOrder order) throws BaseException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result updateOrderForConfirm(EmSOrder order) throws BaseException {
        Result ret = new Result();
        try {
            orderDao.updateEmSOrderForConfirm(order);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("确认收货失败！");
        }
        return ret;
    }

    @Override
    public Result updateEmSOrderDelivery(EmSOrder order) throws BaseException {
        Result ret = new Result();
        try {
            orderDao.updateEmSOrderDelivery(order);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("确认发货失败！");
        }
        return ret;
    }
    
    private boolean isDo() {
        if (null != WebAppConfig.getConfigMapServiceRouter().get("BOOKING_ERP_ORDER") && "true".equals(WebAppConfig.getConfigMapServiceRouter().get("BOOKING_ERP_ORDER"))) {
            return true;
        } else {
            return false;
        }
    }

	@Override
	public EmSOrder getOrderInfo(EmSOrder order) throws BaseException {
		return orderDao.getOrderInfo(order);
	}
}
